package com.yjt.fresh.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.Api.BaseResultEntity;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import com.yjt.fresh.R;
import com.yjt.fresh.api.ApiImageUpload;
import com.yjt.fresh.api.ApiOtherLogin;
import com.yjt.fresh.api.ApiUnBindThirdLogin;
import com.yjt.fresh.api.ApiUpdateUserInfo;
import com.yjt.fresh.api.ApiUpdateUserPhoto;
import com.yjt.fresh.base.BaseSimpleActivity;
import com.yjt.fresh.bean.BeanUploadIMG;
import com.yjt.fresh.bean.BeanUserInfo;
import com.yjt.fresh.bean.JsonBean;
import com.yjt.fresh.constant.MyConstants;
import com.yjt.fresh.dialog.CustomViewBottomDialog;
import com.yjt.fresh.utils.GetJsonDataUtil;
import com.yjt.fresh.utils.PreferenceManager;
import com.yjt.fresh.widget.CustomToastResult;

import org.json.JSONArray;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import jp.wasabeef.glide.transformations.CropCircleTransformation;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static com.yjt.fresh.MyApp.getContext;

/**
 * 个人资料
 * Created by mcc on 2018-07-18.
 */

public class AtyPersonalInfo extends BaseSimpleActivity {
    private static final int REQUEST_CODE = 1008;
    private static final String UNBIND_QQ = "2";
    private static final String UNBIND_WEI_XIN = "1";
    private static final String UNBIND_SINA = "3";
    @BindView(R.id.rlBack)
    RelativeLayout mRlBack;
    @BindView(R.id.ivAppAtyPersonalInfoPhoto)
    ImageView mIvPhoto;
    @BindView(R.id.rlAppAtyPersonalInfoPhoto)
    RelativeLayout mRlPhoto;
    @BindView(R.id.tvAppAtyPersonalInfoNickName)
    TextView mTvNickName;
    @BindView(R.id.rlAppAtyPersonalInfoNickName)
    RelativeLayout mRlNickName;
    @BindView(R.id.tvAppAtyPersonalInfoPhone)
    TextView mTvPhone;
    @BindView(R.id.rlAppAtyPersonalInfoBindPhone)
    RelativeLayout mRlBindPhone;
    @BindView(R.id.tvAppAtyPersonalInfoSex)
    TextView mTvSex;
    @BindView(R.id.rlAppAtyPersonalInfoSex)
    RelativeLayout mRlSex;
    @BindView(R.id.tvAppAtyPersonalInfoArea)
    TextView mTvArea;
    @BindView(R.id.rlAppAtyPersonalInfoArea)
    RelativeLayout mRlArea;
    @BindView(R.id.rlAppAtyPersonalInfoAlterPassword)
    RelativeLayout mRlAlterPassword;
    @BindView(R.id.tvAppAtyPersonalInfoQQ)
    TextView mTvQQ;
    @BindView(R.id.rlAppAtyPersonalInfoQQ)
    RelativeLayout mRlQQ;
    @BindView(R.id.tvAppAtyPersonalInfoWeiXin)
    TextView mTvWeiXin;
    @BindView(R.id.rlAppAtyPersonalInfoWeiXin)
    RelativeLayout mRlWeiXin;
    @BindView(R.id.tvAppAtyPersonalInfoWeiBo)
    TextView mTvWeiBo;
    @BindView(R.id.rlAppAtyPersonalInfoWeiBo)
    RelativeLayout mRlWeiBo;
    private CustomViewBottomDialog mSexBottomDialog;
    private String mSex;
    private ArrayList<JsonBean> options1Items = new ArrayList<>();
    private ArrayList<ArrayList<String>> options2Items = new ArrayList<>();
    private ArrayList<ArrayList<ArrayList<String>>> options3Items = new ArrayList<>();
    private BeanUserInfo mUserInfo;
    private String mArea;
    private String mProvince;
    private String mCity;
    private String mDistrict;
    private String mUnbindType;
    private String mBindType;
    private CustomViewBottomDialog mPhotoBottomDialog;

    @Override
    protected int getContentView() {
        return R.layout.app_aty_personal_info;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        mUserInfo = PreferenceManager.getInstance().getUserInfo();
        Glide.with(mContext)
                .load(mUserInfo.getLOGO_IMG())
                .placeholder(R.mipmap.f1_ic_06)
                .bitmapTransform(new CropCircleTransformation(getContext()))
                .into(mIvPhoto);
        mTvNickName.setText(mUserInfo.getNICKNAME() == null ? "" : mUserInfo.getNICKNAME());
        mTvArea.setText((mUserInfo.getPROVINCE() == null ? "" : mUserInfo.getPROVINCE())
                + " " + (mUserInfo.getCITY() == null ? "" : mUserInfo.getCITY())
                + " " + (mUserInfo.getDISTRICT() == null ? "" : mUserInfo.getDISTRICT()));
        mTvPhone.setText(mUserInfo.getPHONE() == null ? "" : mUserInfo.getPHONE());
        mTvSex.setText(mUserInfo.getSEX() == null ? "" : mUserInfo.getSEX());

        if (!TextUtils.isEmpty(mUserInfo.getQQ_LOGIN_INFO())) {
            mTvQQ.setText("已绑定");
        }

        if (!TextUtils.isEmpty(mUserInfo.getWECHAT_LOGIN_INFO())) {
            mTvWeiXin.setText("已绑定");
        }

        if (!TextUtils.isEmpty(mUserInfo.getSINA_LOGIN_INFO())) {
            mTvWeiBo.setText("已绑定");
        }
    }

    @Override
    protected void initEvent() {
        initClick();
    }


    private void initClick() {
        mRlNickName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, AtyNickName.class);
                startActivityForResult(intent, MyConstants.UPDATE_USER_INFO);
            }
        });

        mRlAlterPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, AtyChangePassword.class);
                startActivity(intent);
            }
        });

        mRlArea.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initAreaData();
            }
        });

        mRlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mRlBindPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (PreferenceManager.getInstance().getUserInfo().getPHONE() != null && PreferenceManager.getInstance().getUserInfo().getPHONE().length() > 0) {
                    Intent intent = new Intent(mContext, AtyChangeBindPhone.class);
                    intent.putExtra(MyConstants.PHONE_NUM, PreferenceManager.getInstance().getUserInfo().getPHONE());
                    startActivityForResult(intent, REQUEST_CODE);
                } else {
                    Intent intent = new Intent(mContext, AtyBindNewPhone.class);
                    startActivityForResult(intent, REQUEST_CODE);
                }
            }
        });

        mRlSex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mSexBottomDialog = new CustomViewBottomDialog(mContext);
                initAlterSexDialogView();
                mSexBottomDialog.builder();

                mSexBottomDialog.show();
            }
        });

        mRlPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alterUserPhoto();
            }
        });

        mRlQQ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String qq_login_info = PreferenceManager.getInstance().getUserInfo().getQQ_LOGIN_INFO();
                if (!TextUtils.isEmpty(qq_login_info)) {
                    String phone = PreferenceManager.getInstance().getUserInfo().getPHONE();
                    if (!TextUtils.isEmpty(phone) ) {
                        //解绑
                        mUnbindType = UNBIND_QQ;
                        unBindThirdLogin();
                    } else {
                        Toast.makeText(mContext, "请先绑定手机号再解绑", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    //绑定
                    mBindType = UNBIND_QQ;
                    bindThirdLogin(SHARE_MEDIA.QQ);
                }
            }
        });

        mRlWeiXin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String wechat_login_info = PreferenceManager.getInstance().getUserInfo().getWECHAT_LOGIN_INFO();
                if (!TextUtils.isEmpty(wechat_login_info)) {
                    String phone = PreferenceManager.getInstance().getUserInfo().getPHONE();
                    if (!TextUtils.isEmpty(phone)) {
                        //解绑
                        mUnbindType = UNBIND_WEI_XIN;
                        unBindThirdLogin();
                    } else {
                        Toast.makeText(mContext, "请先绑定手机号再解绑", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    //绑定
                    mBindType = UNBIND_WEI_XIN;
                    bindThirdLogin(SHARE_MEDIA.WEIXIN);
                }
            }
        });

        mRlWeiBo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String sina_login_info = PreferenceManager.getInstance().getUserInfo().getSINA_LOGIN_INFO();
                if (!TextUtils.isEmpty(sina_login_info)) {
                    String phone = PreferenceManager.getInstance().getUserInfo().getPHONE();
                    if (!TextUtils.isEmpty(phone)) {
                        //解绑
                        mUnbindType = UNBIND_SINA;
                        unBindThirdLogin();
                    } else {
                        Toast.makeText(mContext, "请先绑定手机号再解绑", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    //绑定
                    mBindType = UNBIND_SINA;
                    bindThirdLogin(SHARE_MEDIA.SINA);
                }
            }
        });
    }

    private void bindThird(Map<String, String> map) {
        ApiOtherLogin apiOtherLogin = new ApiOtherLogin(new HttpOnNextListener<BeanUserInfo>() {
            @Override
            public void onNext(BeanUserInfo beanUserInfo) {
                CustomToastResult.show("绑定成功");
                PreferenceManager.getInstance().setIsLogin(true);
                PreferenceManager.getInstance().setUserInfo(beanUserInfo);
                if (UNBIND_QQ.equals(mBindType)) {
                    mTvQQ.setText("已绑定");
                } else if (UNBIND_WEI_XIN.equals(mBindType)) {
                    mTvWeiXin.setText("已绑定");
                } else if (UNBIND_SINA.equals(mBindType)) {
                    mTvWeiBo.setText("已绑定");
                }
            }

            @Override
            public void failed(String massage) {
                super.failed(massage);
                Toast.makeText(mContext, massage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onReLogin() {

            }
        }, mContext, true, false, false);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("LOGIN_INFO", map.get("uid"));
        paramMap.put("THIRD_LOGIN_TYPE", mBindType);
        paramMap.put("NICKNAME", map.get("name"));
        paramMap.put("LOGO_IMG", map.get("iconurl"));
        paramMap.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        apiOtherLogin.setMap(paramMap);
        HttpManager.getInstance().doHttpDeal(apiOtherLogin);
    }

    UMAuthListener mUmAuthListener = new UMAuthListener() {

        private ProgressDialog mProgressDialog;

        @Override
        public void onStart(SHARE_MEDIA share_media) {
            mProgressDialog = new ProgressDialog(mContext);
            mProgressDialog.setMessage("正在绑定...");
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
        }

        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
            if (mProgressDialog != null && mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
            }
            bindThird(map);
        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            if (mProgressDialog != null && mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
            }
            Toast.makeText(mContext, "绑定失败:" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {
            if (mProgressDialog != null && mProgressDialog.isShowing()) {
                mProgressDialog.dismiss();
            }
            Toast.makeText(mContext, "绑定取消了", Toast.LENGTH_SHORT).show();
        }
    };

    private void bindThirdLogin(SHARE_MEDIA share_media) {
        UMShareAPI umShareAPI = UMShareAPI.get(mContext);
        umShareAPI.getPlatformInfo(mContext, share_media, mUmAuthListener);
    }

    private void unBindThirdLogin() {
        ApiUnBindThirdLogin apiUnBindThirdLogin = new ApiUnBindThirdLogin(new HttpOnNextListener<BaseResultEntity>() {

            @Override
            public void onNext(BaseResultEntity baseResultEntity) {
                CustomToastResult.show("解绑成功");
                PreferenceManager preferenceManager = PreferenceManager.getInstance();
                BeanUserInfo userInfo = preferenceManager.getUserInfo();
                switch (mUnbindType) {
                    case UNBIND_QQ:
                        userInfo.setQQ_LOGIN_INFO(null);
                        preferenceManager.setUserInfo(userInfo);
                        mTvQQ.setText("");
                        break;
                    case UNBIND_WEI_XIN:
                        userInfo.setWECHAT_LOGIN_INFO(null);
                        preferenceManager.setUserInfo(userInfo);
                        mTvWeiXin.setText("");
                        break;
                    case UNBIND_SINA:
                        userInfo.setSINA_LOGIN_INFO(null);
                        preferenceManager.setUserInfo(userInfo);
                        mTvWeiBo.setText("");
                        break;
                }
            }

            @Override
            public void failed(String massage) {
                super.failed(massage);
                Toast.makeText(mContext, massage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onReLogin() {

            }
        }, mContext, true, false, false);
        Map<String, Object> map = new HashMap<>();
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        map.put("THIRD_LOGIN_TYPE", mUnbindType);
        apiUnBindThirdLogin.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiUnBindThirdLogin);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mTvPhone.setText(PreferenceManager.getInstance().getUserInfo().getPHONE());
    }

    private void alterUserPhoto() {
        if (mPhotoBottomDialog == null) {
            mPhotoBottomDialog = new CustomViewBottomDialog(mContext);
            initAlterPhotoDialogView();
            mPhotoBottomDialog.builder();
        }

        mPhotoBottomDialog.show();
    }

    private void initAlterPhotoDialogView() {
        View view = View.inflate(mContext, R.layout.app_dialog_alter_photo, null);
        TextView tvCamera = view.findViewById(R.id.tvAppDialogAlterPhotoCamera);
        TextView tvAlbum = view.findViewById(R.id.tvAppDialogAlterPhotoAlbum);
        TextView tvCancel = view.findViewById(R.id.tvAppDialogAlterPhotoCancel);
        mPhotoBottomDialog.setView(view);

        tvCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, ImageGridActivity.class);
                intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true); // 是否是直接打开相机
                startActivityForResult(intent, MyConstants.PICK_IMG);
                mPhotoBottomDialog.dismiss();
            }
        });

        tvAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mContext, ImageGridActivity.class);
                startActivityForResult(intent, MyConstants.PICK_IMG);
                mPhotoBottomDialog.dismiss();
            }
        });

        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPhotoBottomDialog != null) {
                    mPhotoBottomDialog.dismiss();
                }
            }
        });
    }

    private void initAlterSexDialogView() {
        View view = View.inflate(mContext, R.layout.app_dialog_alter_photo, null);
        TextView tvMale = view.findViewById(R.id.tvAppDialogAlterPhotoCamera);
        TextView tvFemale = view.findViewById(R.id.tvAppDialogAlterPhotoAlbum);
        TextView tvCancel = view.findViewById(R.id.tvAppDialogAlterPhotoCancel);
        if ("男".equals(mUserInfo.getSEX())) {
            tvMale.setTextColor(getResources().getColor(R.color.color_3992f8));
            tvFemale.setTextColor(getResources().getColor(R.color.color_222222));
        } else if ("女".equals(mUserInfo.getSEX())) {
            tvMale.setTextColor(getResources().getColor(R.color.color_222222));
            tvFemale.setTextColor(getResources().getColor(R.color.color_3992f8));
        } else {
            tvMale.setTextColor(getResources().getColor(R.color.color_222222));
            tvFemale.setTextColor(getResources().getColor(R.color.color_222222));
        }
        tvMale.setText("男");
        tvFemale.setText("女");
        mSexBottomDialog.setView(view);

        tvMale.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateUserSex("男");
                mSexBottomDialog.dismiss();
            }
        });

        tvFemale.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateUserSex("女");
                mSexBottomDialog.dismiss();
            }
        });

        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

    HttpOnNextListener<BaseResultEntity> mListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            CustomToastResult.show("设置成功");
            BeanUserInfo userInfo = PreferenceManager.getInstance().getUserInfo();
            userInfo.setSEX(mSex);
            mUserInfo.setSEX(mSex);
            PreferenceManager.getInstance().setUserInfo(userInfo);
            mTvSex.setText(mSex);
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void updateUserSex(String sex) {
        mSex = sex;
        ApiUpdateUserInfo apiUpdateUserInfo = new ApiUpdateUserInfo(mListener, mContext, true, false, true);
        Map<String, Object> map = new HashMap<>();
        map.put("SEX", sex);
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        apiUpdateUserInfo.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiUpdateUserInfo);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (requestCode == MyConstants.PICK_IMG && resultCode == ImagePicker.RESULT_CODE_ITEMS && data != null) {
            ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            Glide.with(mContext)
                    .load(images.get(0).path)
                    .bitmapTransform(new CropCircleTransformation(mContext))
                    .into(mIvPhoto);
            uploadImage(images.get(0).path);
        }
        if (requestCode == MyConstants.UPDATE_USER_INFO) {
            BeanUserInfo userInfo = PreferenceManager.getInstance().getUserInfo();
            mTvNickName.setText(userInfo.getNICKNAME());
        }

        if (requestCode == REQUEST_CODE) {
            mTvPhone.setText(PreferenceManager.getInstance().getUserInfo().getPHONE());
        }
    }

    private String mIMGUrl;
    //   回调一一对应
    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BeanUploadIMG>() {
        @Override
        public void onNext(BeanUploadIMG data) {
            mIMGUrl = data.getIMG_URL();
            updateUserLogo(mIMGUrl);

        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void uploadImage(String path) {
        File file = new File(path);
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"), file);
        MultipartBody.Part part1 = MultipartBody.Part.createFormData("IMG", file.getName(), requestBody);
        ApiImageUpload postEntity = new ApiImageUpload(simpleOnNextListener, mContext, false, false, true);
        postEntity.setPart(part1);
        HttpManager manager = HttpManager.getInstance();
        manager.doHttpDeal(postEntity);
    }

    HttpOnNextListener<BaseResultEntity> mUpdateUserPhotoListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            CustomToastResult.show("设置成功");
            PreferenceManager manager = PreferenceManager.getInstance();
            BeanUserInfo userInfo = manager.getUserInfo();
            userInfo.setLOGO_IMG(mIMGUrl);
            manager.setUserInfo(userInfo);
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void updateUserLogo(String url) {
        ApiUpdateUserPhoto apiUpdateUserPhoto = new ApiUpdateUserPhoto(mUpdateUserPhotoListener, mContext, true, false, true);
        Map<String, Object> map = new HashMap<>();
        map.put("LOGO_IMG", url);
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        apiUpdateUserPhoto.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiUpdateUserPhoto);
    }

    private void showPickerView() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                mProvince = options1Items.get(options1).getPickerViewText();
                mCity = options2Items.get(options1).get(options2);
                mDistrict = options3Items.get(options1).get(options2).get(options3);
                mArea = mProvince +
                        " " + mCity +
                        " " + mDistrict;
                updateUserArea();
            }
        })

                .setTitleText("城市选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .build();

        /*pvOptions.setPicker(options1Items);//一级选择器
        pvOptions.setPicker(options1Items, options2Items);//二级选择器*/
        pvOptions.setPicker(options1Items, options2Items, options3Items);//三级选择器
        pvOptions.show();
    }

    HttpOnNextListener<BaseResultEntity> mUpdateUserAreaListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            CustomToastResult.show("设置成功");
            PreferenceManager manager = PreferenceManager.getInstance();
            BeanUserInfo userInfo = manager.getUserInfo();
            userInfo.setPROVINCE(mProvince);
            userInfo.setCITY(mCity);
            userInfo.setDISTRICT(mDistrict);
            manager.setUserInfo(userInfo);
            mTvArea.setText(mArea);
        }

        @Override
        public void onReLogin() {
            toLogin();
        }
    };

    private void updateUserArea() {
        ApiUpdateUserInfo apiUpdateUserInfo = new ApiUpdateUserInfo(mUpdateUserAreaListener, mContext, true, false, true);
        Map<String, Object> map = new HashMap<>();
        map.put("PROVINCE", mProvince);
        map.put("CITY", mCity);
        map.put("DISTRICT", mDistrict);
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        apiUpdateUserInfo.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiUpdateUserInfo);
    }

    private void initAreaData() {//解析数据

        /**
         * 注意：assets 目录下的Json文件仅供参考，实际使用可自行替换文件
         * 关键逻辑在于循环体
         *
         * */
        String JsonData = new GetJsonDataUtil().getJson(this, "province.json");//获取assets目录下的json文件数据

        ArrayList<JsonBean> jsonBean = parseData(JsonData);//用Gson 转成实体

        /**
         * 添加省份数据
         *
         * 注意：如果是添加的JavaBean实体，则实体类需要实现 IPickerViewData 接口，
         * PickerView会通过getPickerViewText方法获取字符串显示出来。
         */
        options1Items = jsonBean;

        for (int i = 0; i < jsonBean.size(); i++) {//遍历省份
            ArrayList<String> CityList = new ArrayList<>();//该省的城市列表（第二级）
            ArrayList<ArrayList<String>> Province_AreaList = new ArrayList<>();//该省的所有地区列表（第三极）

            for (int c = 0; c < jsonBean.get(i).getCityList().size(); c++) {//遍历该省份的所有城市
                String CityName = jsonBean.get(i).getCityList().get(c).getName();
                CityList.add(CityName);//添加城市
                ArrayList<String> City_AreaList = new ArrayList<>();//该城市的所有地区列表

                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (jsonBean.get(i).getCityList().get(c).getArea() == null
                        || jsonBean.get(i).getCityList().get(c).getArea().size() == 0) {
                    City_AreaList.add("");
                } else {
                    City_AreaList.addAll(jsonBean.get(i).getCityList().get(c).getArea());
                }
                Province_AreaList.add(City_AreaList);//添加该省所有地区数据
            }

            /**
             * 添加城市数据
             */
            options2Items.add(CityList);

            /**
             * 添加地区数据
             */
            options3Items.add(Province_AreaList);
        }

        showPickerView();

    }


    public ArrayList<JsonBean> parseData(String result) {//Gson 解析
        ArrayList<JsonBean> detail = new ArrayList<>();
        try {
            JSONArray data = new JSONArray(result);
            Gson gson = new Gson();
            for (int i = 0; i < data.length(); i++) {
                JsonBean entity = gson.fromJson(data.optJSONObject(i).toString(), JsonBean.class);
                detail.add(entity);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }

}
